package com.star.config.biz;

import com.star.common.cache.StarRedisTemplate;
import com.star.common.cache.annotation.StarRedis;
import com.star.common.core.contract.exception.ServiceException;
import com.star.common.core.utils.BeanKit;
import com.star.config.api.contract.query.UserTenantConfigQuery;
import com.star.config.api.contract.vo.UserTenantConfigVO;
import com.star.config.contract.constant.ConfigRedisKeyConstant;
import com.star.config.contract.enums.ConfigErrorEnum;
import com.star.config.contract.param.UserTenantConfigParam;
import com.star.config.repository.model.UserTenantConfigBO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author zhouhengzhe
 * 应用配置(UserTenantConfig)表领域处理服务类
 * @date 2023-12-30 23:33:50
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserTenantConfigService {

    @StarRedis("redis:config")
    private final StarRedisTemplate starRedisTemplate;

    /**
     * 根据租户id查询应用配置
     *
     * @param query 查询参数
     * @return UserTenantConfigVO
     */
    public UserTenantConfigVO getUserTenantConfig(UserTenantConfigQuery query) {
        //先从Redis缓存中获取
        String key = ConfigRedisKeyConstant.USER_TENANT_CONFIG_KEY + query.getTenantId();
        //如果redis中有key，则直接返回
        if (starRedisTemplate.hasKey(key)) {
            return BeanKit.copy(starRedisTemplate.get(key), UserTenantConfigVO.class);
        }
        //如果缓存中没有，则从数据库中获取
        UserTenantConfigBO userTenantConfigBO = UserTenantConfigParam.builder().tenantId(query.getTenantId()).build().one();
        if (Objects.isNull(userTenantConfigBO)) {
            throw new ServiceException(ConfigErrorEnum.TENANT_ID_NOT_EXIST);
        }
        //将数据存入Redis缓存中
        starRedisTemplate.set(key, userTenantConfigBO);
        return BeanKit.copy(userTenantConfigBO, UserTenantConfigVO.class);
    }
}
